package com.example.retrofit;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="tag";
    public static final MediaType JSON=MediaType.get("application/json; charset=utf-8");



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
        Button btnSendGet=findViewById(R.id.btn_get);
        Button btnSendPost=findViewById(R.id.btn_post);
        //创建OkHttpClient  拦截器
        OkHttpClient client=new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        Request request=chain.request();
                        //登录后后台返回的认证，防止被服务篡改抓包
                        request.newBuilder().addHeader("authorization","xxxx");
                        //登录后服务端返回的会话ID，用于长登录的维持会话作用
                        request.newBuilder().addHeader("session_id/token","xxxx");
                        long startTime=System.currentTimeMillis();
                        Response response=chain.proceed(chain.request());
                        long endTime=System.currentTimeMillis();
                        long duration=endTime-startTime;
                        MediaType mediaType=response.body().contentType();
                        String content=response.body().string();
                        Log.e("请求地址","intercept:"+request.toString());
                        Log.e("返回数据","intercept:"+content);
                        Log.e("数据格式","intercept:"+mediaType);
                        Log.e("时间","--------请求耗时："+duration+"毫秒--------");


                        return response.newBuilder().body(ResponseBody.create(mediaType,content)).build() ;
                    }
                }).build();
        btnSendGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建请求体
                Request request=new Request.Builder().url("http://apis.juhe.cn/simpleWeather/query?city=655&key=8cf90bdd00d8ff3b42af97f57977b8ba").build();
                //发送请求 client.newCall(request).execute()方法为同步方法，需要添加子线程发送
                //client.newCall(request).enqueue()方法为异步方法，通过监听回调方式接收
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String jsonStr=response.body().string();
                        Log.d(TAG,"城市天气："+jsonStr);

                    }
                });
            }
        });

        btnSendPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //RequestBody body=RequestBody.create("", JSON);
                RequestBody body=new FormBody.Builder().add("city","655")
                        .add("key","8cf90bdd00d8ff3b42af97f57977b8ba").build();
                //url("http://apis.juhe.cn/simpleWeather/query?city=655&key=8cf90bdd00d8ff3b42af97f57977b8ba")
                Request request=new Request.Builder()
                        .url("http://apis.juhe.cn/simpleWeather/query")
                        .post(body)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String jsonStr=response.body().string();
                        Log.d(TAG,"post城市天气："+jsonStr);

                    }
                });
            }
        });
    }
}